<template>
  <div>
    <el-tag
      v-for="(item,k) in tagList"
      :key="k"
      :disable-transitions="false"
      :type="item.type">
      {{item.tag}}
    </el-tag>
    <el-input
      class="input-new-tag"
      v-if="isTagInput"
      v-model="tagInputValue"
      ref="saveTagInput"
      size="small"
      @keyup.enter.native="handleInputConfirm"
      @blur="handleInputConfirm"
    >
    </el-input>
    <el-button v-else class="button-new-tag" size="small" @click="showTagInput">+ New Tag</el-button>
  </div>
</template>

<script>
  import {queryTags, addAndUpdateTag} from "../../assets/api/getData";

  export default {
    name: "tagManage",
    data() {
      return {
        isTagInput: false,
        tagInputValue: '',
        isDialog: false,
        tagList: []
      }
    },
    created() {
      this.getTagList();
    },
    methods: {
      showTagInput() {
        this.isTagInput = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
      async handleInputConfirm() {
        let inputValue = this.tagInputValue;
        if (inputValue) {
          let index = this.tagList.findIndex(item => {
            return item.tag == inputValue
          });
          if (index >= 0) {
            this.$message.warning("标签名已存在");
            return
          }
          let res = await addAndUpdateTag({
            id: null,
            tag: inputValue,
          });
          this.getTagList();
        }
        this.isTagInput = false;
        this.tagInputValue = '';
      },
      async getTagList() {
        let {data} = await queryTags();
        this.tagList = data;
        let typeList = ['', 'success', 'info', 'danger', 'warning'];
        this.tagList.forEach(item => {
          let num = Math.floor(Math.random() * 5);
          item.type = typeList[num]
        })
      }
    }
  }
</script>

<style scoped>

</style>
